//
//  LearningViewController.swift
//  ddx0513
//
//  Created by shuijing on 15/7/21.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import UIKit

//定义协议传递sectionid值
protocol DeliverSectionidDelegate:NSObjectProtocol{
    //回调方法
    func deliverSectionid(sectionId: Int,imgUrl: String)
    //全屏播放
    func playInFullScreen()
    //判断是否免费
    func isFree(freeType:Int)
    //无权限用户设置播放器首帧图片
    func setVideoImg(imgUrl: String)
}
class LearningViewController: UITableViewController {
    var delegate:DeliverSectionidDelegate?
    
    var lessonnameArr:NSMutableArray = []
    var totalSectionNum = 0
    var chapterName:NSMutableArray = []
    var sectionName:NSMutableArray = []
    var sectionId:NSMutableArray = []
    var sectionImg:NSMutableArray = []
    var chatperId = 0
    var sectionSubnum = 0
    // var isChapter:Bool = false
    var isChapter:NSMutableArray = []
    var studied:NSMutableArray = []
    var progress:NSMutableArray = []
    var isStudiedChapter:NSMutableArray = []
    var kindOfImage:Int = 0
    var datas:Int = 18
    var lessonId:Int!
    var lastStudySectionId:Int = 0
    var isFree:NSMutableArray = []//0收费 1免费
    var isFirst:Bool = true
    var courseImgUrl = ""
    var hud: MBProgressHUD?
    var lineArr:NSMutableArray = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.tableFooterView = UIView(frame: CGRectZero)
        
        var header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: Selector("getLearningCourse"))
        header.lastUpdatedTimeLabel.hidden = true
        self.tableView.header = header
        self.tableView.header.beginRefreshing()
        //getLearningCourse()

    }
    func getFree()
    {
        if (totalSectionNum >= 1)
        {
                var freeOrnot:Int = isFree.objectAtIndex(1) as! Int
                if(freeOrnot==1)
                {
                    self.delegate?.isFree(1)
                }
                else
                {
                   self.delegate?.isFree(0)                }
            
        }
    }
    func getDeliver()
    {
        var first = sectionId.objectAtIndex(1) as! Int
        if (DBUtils.mem.loginStatus)//登陆状态
        {
            if (totalSectionNum >= 1) {
                if(lastStudySectionId == 0)//没有学习记录
                {
                    var freeOrnot:Int = isFree.objectAtIndex(1) as! Int
                    if(freeOrnot==1)//是否有免费章节
                    {
                        var last = sectionId.objectAtIndex(1) as! Int
                        self.delegate?.deliverSectionid( last, imgUrl: "")
                    }
                    else
                    {
                        if (DBUtils.mem.vipType == "NONE_VIP")
                        {
                            self.delegate?.setVideoImg(courseImgUrl)
                        }
                        else
                        {
                            self.delegate?.deliverSectionid(first, imgUrl: "")
                        }
                        
                    }
                }
                else
                {
                    if (DBUtils.mem.vipType == "NONE_VIP")
                    {
                        var freeOrnot:Int = isFree.objectAtIndex(1) as! Int
                        if(freeOrnot==1)
                        {
                            var last = sectionId.objectAtIndex(1) as! Int
                            self.delegate?.deliverSectionid( last, imgUrl: "")
                        }
                        else
                        {
                            self.delegate?.setVideoImg(courseImgUrl)
                            
                        }
                        
                    }
                    else
                    {
                        self.delegate!.deliverSectionid(lastStudySectionId, imgUrl: "")
                    }
                }
                
            }
            else
            {
                //self.delegate!.deliverSectionid(0, imgUrl: "")
            }
        }
        else
        {
            self.delegate?.setVideoImg(courseImgUrl)
        }
        
    }
    
    
    
    func delay(delay:Double, closure:()->()) {
        
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(delay * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), closure)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func getLearningCourse(){
        
        var userid:Int = DBUtils.mem.userId
        var token:String = DBUtils.mem.token
        NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLLessonInfo() , parameters: ["userid":userid,"token":token,"lessonid":lessonId], responseHandler: nil, netErrorHandler: errorHandler, successHandler: learningTableview, interErrorHandler: interErrorHandler, jsonErrorHandler: errorHandler)
    }
    
    func errorHandler() {
        self.tableView.header.endRefreshing()
        MBHudUtils.showText("加载失败", view: self.view)
    }
    
    func interErrorHandler(retCode: Int, retMsg: String) {
        self.tableView.header.endRefreshing()
        MBHudUtils.showText("加载失败", view: self.view)
    }
    
    func learningTableview (json: JSON) {
        //totalSectionNum = json["sectionnum"].int!
        //totalSectionNum = json[]
        lastStudySectionId = json["laststudysectionid"].int!
        courseImgUrl = json["imgurl"].string!
        var test = json["chapters"][0]["sections"].count
        var k = 0
        var lastSection:Bool = false
        var isStudied:Bool = false
        var isProgressed = 0
        chatperId = json["chapters"].count
        for (var i = chatperId-1;i >= 0; i-- )
        {
            
            lessonnameArr.addObject(json["chapters"][i]["chaptername"].string!)
            isChapter.addObject(true)
            sectionSubnum = json["chapters"][i]["sections"].count
            sectionId.addObject(0)
            sectionImg.addObject("img")
            //表示章
            isFree.addObject(2)
            //线的用法1表示章，2表示第一节，3表示最后一节
            lineArr.addObject(1)
            studied.addObject(0)
            progress.addObject(0)
            for (var j = sectionSubnum-1;j >= 0; j-- )
            {
                totalSectionNum++
                isStudied = json["chapters"][i]["sections"][j]["studied"].bool!
                isProgressed = json["chapters"][i]["sections"][j]["progress"].int!
                if (j==sectionSubnum-1)
                {
                    lineArr.addObject(2)//最后一节
                    if( isStudied ){
                        isStudiedChapter.addObject(1)
                        isStudiedChapter.addObject(1)
                    }
                    else if(!isStudied && isProgressed != 0){
                        isStudiedChapter.addObject(1)
                        isStudiedChapter.addObject(2)
                        
                    }
                    else if(!isStudied && isProgressed == 0){
                        isStudiedChapter.addObject(3)
                        isStudiedChapter.addObject(3)
                        
                    }
                    
                    
                }
                else if (j==0)
                {
                    lineArr.addObject(3)//第一节
                    if( isStudied ){
                        isStudiedChapter.addObject(1)
                    }
                    else if(!isStudied && isProgressed != 0){
                        isStudiedChapter.addObject(2)
                        
                    }
                    else if(!isStudied && isProgressed == 0){
                        isStudiedChapter.addObject(3)
                        
                    }

                }
                else
                {
                    lineArr.addObject(0)
                    if( isStudied ){
                        isStudiedChapter.addObject(1)
                    }
                    else if(!isStudied && isProgressed != 0){
                        isStudiedChapter.addObject(2)
                        
                    }
                    else if(!isStudied && isProgressed == 0){
                        isStudiedChapter.addObject(3)
                        
                    }
                    
                    
                }
                
                studied.addObject(json["chapters"][i]["sections"][j]["studied"].bool!)
                
                lessonnameArr.addObject(json["chapters"][i]["sections"][j]["sectionname"].string!)
                isChapter.addObject(false)
                progress.addObject(json["chapters"][i]["sections"][j]["progress"].int!)
                sectionId.addObject(json["chapters"][i]["sections"][j]["sectionid"].int!)
                sectionImg.addObject(json["chapters"][i]["sections"][j]["imgurl"].string!)
                isFree.addObject(json["chapters"][i]["sections"][j]["free"].int!)
            }
            
        }
         tableView.reloadData()
        self.tableView.header.endRefreshing()
        self.tableView.header.hidden = true
        
    }
    
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        
        // println(lessonnameArr.count)
        // return lessonnameArr.count
        
        
        // println("datas")
        // println(self.datas)
        /*if(lessonnameArr.count < self.datas)
        {
            return lessonnameArr.count
        }
        else
        {
            return self.datas
        }*/
        //return 1
        //println(lessonnameArr.count)
        return lessonnameArr.count
        
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // UITableViewCellSeparatorStyleNone
        var tableCell :LearningItem = tableView.dequeueReusableCellWithIdentifier("learning") as! LearningItem
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        //println(isChapter.count)
        
        if (lessonnameArr.count == 0)
        {
            return tableCell
        }
        var s = lessonnameArr.objectAtIndex(indexPath.row) as? String

        var b = isChapter.objectAtIndex(indexPath.row) as! Bool
        if(b == true)//章
        {
            tableCell.selectionStyle = UITableViewCellSelectionStyle.None
            tableCell.chapterName.text = s
            tableCell.chapterName.textColor = UIColor.blackColor()
            tableCell.chapterName.font = UIFont.boldSystemFontOfSize(17)
            
            
            
        }
        else//节
        {
            tableCell.chapterName.text = s
            tableCell.chapterName.textColor = UIColor.darkGrayColor()
            tableCell.chapterName.font = UIFont.systemFontOfSize(14)
        }
        var m = isStudiedChapter.objectAtIndex(indexPath.row) as! Int
        var line = lineArr.objectAtIndex(indexPath.row) as! Int
        if(b == true){
            tableCell.progressIMg.image = UIImage(named: "")
            tableCell.topLine.image = UIImage(named: "")
            tableCell.bottomLine.image = UIImage(named: "")
        }
        else {
            if (m == 1){
                tableCell.progressIMg.image = UIImage(named: "教程详情-继续学习_17@2x.png")
            }else if(m == 2){
                tableCell.progressIMg.image = UIImage(named: "教程详情-继续学习_20@2x.png")
                
            }else{
                tableCell.progressIMg.image = UIImage(named: "教程详情-开始学习_05@2x.png")
                
            }
            if(totalSectionNum == 1){
                tableCell.topLine.image = UIImage(named: "")
                tableCell.bottomLine.image = UIImage(named: "")
            }
            else if(line == 2){//第一节
                tableCell.topLine.image = UIImage(named: "")
                tableCell.bottomLine.image = UIImage(named: "学习进度线2.png")
            }
            else if(line == 3){
                tableCell.topLine.image = UIImage(named: "学习进度线2.png")
                tableCell.bottomLine.image = UIImage(named: "")
            }
            else{
                tableCell.topLine.image = UIImage(named: "学习进度线2.png")
                tableCell.bottomLine.image = UIImage(named: "学习进度线2.png")
            }
        }
        
        if((delegate) != nil){
        
            if (isFirst)
            {
                getDeliver()
                getFree()
                isFirst = false
            }
            

        }
        
        return tableCell
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var s = sectionId.objectAtIndex(indexPath.row) as? Int

        var freeOrnot = isFree.objectAtIndex(indexPath.row) as! Int
        var b = isChapter.objectAtIndex(indexPath.row) as! Bool
        if(b == true)
        {
        }

        if(DBUtils.mem.loginStatus)
        {
            if (DBUtils.mem.vipType == "NONE_VIP")//判断免费章节，转购买界面
            {
                if(freeOrnot==1){
                    self.delegate!.deliverSectionid(s!, imgUrl: "")
                }
                else
                {
                    var viewController = UIStoryboard(name: "Setting", bundle: nil).instantiateViewControllerWithIdentifier("Payment") as! PaymentViewController
                    rootController.navigationController?.pushViewController(viewController,animated:true)
                    self.navigationController?.setNavigationBarHidden(false, animated: true)
                }
            }
            else//直接播放
            {
                self.delegate!.deliverSectionid(s!, imgUrl: "")
            }
        }
        else
        {
            var viewController = UIStoryboard(name: "Login", bundle: nil).instantiateViewControllerWithIdentifier("Login") as! LoginViewController
            viewController.sourceNavi = false
            
            rootController.navigationController?.pushViewController(viewController,animated:true)
            self.navigationController?.setNavigationBarHidden(false, animated: true)
            
        }
        //self.delegate!.deliverSectionid(s!, imgUrl: "")
        
    }
    
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */
    
}
